package fr.labri.buganalyzer;

import java.util.List;

import fr.labri.buganalyzer.extractors.BugzillaExtractor;
import fr.labri.buganalyzer.model.Change;
import fr.labri.buganalyzer.model.Issue;
import fr.labri.buganalyzer.writers.H2Adapter;

public class BugAnalyzer {

	private BugzillaExtractor extractor;
	private H2Adapter writer;
	private String type;

	public BugAnalyzer(String trkURL, String type, String dbFile) {
		this.type = type;
		extractor = new BugzillaExtractor(trkURL);
		writer = new H2Adapter(dbFile);
	}

	/**
	 * Gets an XML file and store contained issues with related 
	 * histories into the DB
	 * @param xml file
	 */
	public void storeIssuesFromFile(String file, boolean extractHistories) {
		extractor.extractAllBugsFromXmlFile(file);
		if (extractHistories) 
			extractor.extractAllBugsHistories();
		writer.save(extractor);
		writer.commit();
	}
	
	@Deprecated
	public void storeHistories() {
		H2Adapter adapter = getWriter();
		BugzillaExtractor extractor = getExtractor();
		adapter.loadIssues();
		List<Issue> list = adapter.getIssues();
		List<Change> history;
		for (Issue i : list) {
			try {
				history = extractor.extractBugHistory(i.getNumber());
				Thread.sleep(500);
				System.out.println("Geting history for issue N°: " + i.getNumber());
				if (history != null) {
					for (Change c : history){
						c.setIssue(i);
						adapter.save(c);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		adapter.commit();
		adapter.getSession().close();
	}
	
	public BugzillaExtractor getExtractor() {
		return extractor;
	}

	public void setExtractor(BugzillaExtractor extractor) {
		this.extractor = extractor;
	}
	
	public H2Adapter getWriter() {
		return writer;
	}

	public void setWriter(H2Adapter writer) {
		this.writer = writer;
	}
}
